package com.zhongjianjian.dubbo.server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @类名: com.zhongjianjian.dubbo.server
 * @作者: lgt
 * @创建时间: 2020-03-04 21:44
 * @描述:
 **/
public class TestAServer {

    public static void main(String[] args) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
        //创建服务端连接
        ServerSocket serverSocket = new ServerSocket();
        serverSocket.bind(new InetSocketAddress("127.0.0.1",888));
        //因为是服务端,所以要一直运行
        while (true){
            //等待客户端请求
            Socket accept = serverSocket.accept();
            //读出客户端的请求
            ObjectInputStream objectInputStream = new ObjectInputStream(accept.getInputStream());
            //读出接口参数数组
            Object[] o = (Object[]) objectInputStream.readObject();
            //读出方法的名字信息
            String methodName = objectInputStream.readUTF();
            //读出实现类的名字
            String implName = objectInputStream.readUTF();
            //读出接口参数类型数组
            Class<?>[] paramclass = (Class<?>[]) objectInputStream.readObject();

            //处理客户端发来的请求
            Class<?> aClass = Class.forName(implName);
            //可以通过类class获取spring容器中的注入的类实例  dubbo框架是这么做的
            //我们自己做的dubbo的原理实现比较简陋直接反射生成一个实例

            Object o1 = aClass.newInstance();

            //获取要调用的接口的Method对象
            Method method = aClass.getMethod(methodName, paramclass);
            //执行这个method
            Object invoke = method.invoke(o1, o);
            //把上述的结果发送给客户端
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(accept.getOutputStream());
            //写结果会客户端
            objectOutputStream.writeObject(invoke);
        }
    }
}
